
//
//  GBNetWorking.m
//
//  Created by 密坚 on 15/3/17.
//  Copyright © 2016年 xy. All rights reserved.
//

#import "GBNetWorking.h"
//解析
#import "GBNetWorking+json.h"
//加密
#import "GBNetWorking+encrypt.h"
#import "UserInfoManager.h"
#import "NSError+YU.h"


@interface GBNetWorking()

@property(nonatomic,strong)NSMutableDictionary *requestDic;
@end
@implementation GBNetWorking

/*
 1:创建单利对象
 2:host 网站前坠
 */

+ (instancetype)sharedNetworkTool {
    static GBNetWorking *netWork = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        netWork = [[self alloc]init];
        netWork.requestDic = [NSMutableDictionary dictionary];
        
        });
    return netWork;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.netTool = [MCNetTool sharedTool];
    }
    return self;
}

//-(BOOL)onStopNetworkMonitor{
//    
//    [self.reachabilityManager stopMonitoring];
//    return YES;
//}





#pragma mark-------判断网络状态
-(BOOL)connectedToNetwork{
    
    //创建零地址，0.0.0.0的地址表示查询本机的网络连接状态
    
    struct sockaddr_storage zeroAddress;
    
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.ss_len = sizeof(zeroAddress);
    zeroAddress.ss_family = AF_INET;
    
    // Recover reachability flags
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    
    //获得连接的标志
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
    
    //如果不能获取连接标志，则不能连接网络，直接返回
    if (!didRetrieveFlags)
    {
        return NO;
    }
    //根据获得的连接标志进行判断
    
    BOOL isReachable = flags & kSCNetworkFlagsReachable;
    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
    return (isReachable&&!needsConnection) ? YES : NO;
}


/********************
激活数据库（根据loginId获取不同的数据、库）
 *******************/


/********************
 激活数据库（根据loginId获取不同的数据、库）
 *******************/
#pragma mark - 其他配置
//[self.baseURL ]
- (NSString *)keyWithParameters:(id)param{
    return [NSString zb_stringUTF8Encoding:[NSString zb_urlString:host appendingParameters:param]];
}

- (void)storeObject:(NSObject *)object request:(id)param{
    NSString * key = [self keyWithParameters:param];
    [[ZBCacheManager sharedInstance] storeContent:object forKey:key isSuccess:^(BOOL isSuccess) {
        NSLog(@"保存成功%d",isSuccess);
    }];
}

- (void)storeObject:(NSObject *)object requestForKey:(id)key
{
    
    
    if (![[ZBCacheManager sharedInstance]diskCacheExistsWithKey:key]) {
        [[ZBCacheManager sharedInstance] storeContent:object forKey:key isSuccess:^(BOOL isSuccess) {
            NSLog(@"保存成功%d",isSuccess);
        }];
    }
    else
    {
        [[ZBCacheManager sharedInstance]clearCacheForkey:key completion:^{
            [[ZBCacheManager sharedInstance] storeContent:object forKey:key isSuccess:^(BOOL isSuccess) {
                NSLog(@"保存成功%d",isSuccess);
            }];
        }];
        
    }
    
    
}



//
//- (void)POST:(NSString *)url
//       param:(NSDictionary *)param
//         key:(NSString *)key
//       cache:(BOOL)cache
//  parseClass:(Class)aClass
//successBlock:(successBlock)successBlcok
//  falieBlock:(failedBlock)failedBlcok
//  errorBlock:(errorBlock)errorBlcok
//{
//    
//    WSELF(weakSelf);
//    param = [self onSetUpdateParam:param];
//    
//    [self POST:url parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
//        
//    } success:^(NSURLSessionDataTask * _Nonnull task,NSDictionary *  _Nullable responseObject) {
//        if (cache==YES) {
//            [weakSelf  storeObject:responseObject requestForKey:key];
//        }
//        
//        [GBNetWorking checkHTTPStatusCodeWithModel:^(BOOL success, NSError *error, id model) {
//            
//            if (success) {
//                if (successBlcok) {
//                    successBlcok(model);
//                }
//            }else
//            {
//                if (failedBlcok) {
//                    failedBlcok(error.localizedDescription);
//                }
//            }
//            
//        }](task,responseObject,aClass);
//        
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        
//    }];
//    
//    
//}
- (void)POSTNoToKen:(NSString *)url
              param:(id)param
       successBlock:(void (^)(id data))successBlcok
         falieBlock:(void (^)(NSString *error))failedBlcok
         errorBlock:(void (^)(id error))errorBlcok
{
//      [self.netTool.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    //NSDictionary *header = @{@"Content-Type" : @"application/json"};
    [self POST:url param:param read:NO cache:NO parseClass:nil successBlock:successBlcok falieBlock:failedBlcok errorBlock:errorBlcok];
}
- (void)POST:(NSString *)url
       param:(id)param
  parseClass:(Class)aClass
successBlock:(void (^)(id data))successBlcok
  falieBlock:(void (^)(NSString *error))failedBlcok
  errorBlock:(void (^)(id error))errorBlcok
{
    
    [self POST:url param:param read:NO cache:NO parseClass:aClass successBlock:successBlcok falieBlock:failedBlcok errorBlock:errorBlcok];
}

- (void)POST:(NSString *)url
       param:(id)param
        read:(BOOL)read
       cache:(BOOL)cache
  parseClass:(Class)aClass
successBlock:(void (^)(id data))successBlcok
  falieBlock:(void (^)(NSString *error))failedBlcok
  errorBlock:(void (^)(id error))errorBlcok
{
    if (read) {
        NSString * key = [self keyWithParameters:param];
        WSELF(weakSelf);
        [[ZBCacheManager sharedInstance]getCacheDataForKey:key value:^(id responseObject, NSString *filePath) {
            
            if (responseObject) {
                
                [GBNetWorking checkHTTPStatusCodeWithModel:^(BOOL success, NSError *error, id model) {
                    if (success) {
                        if (successBlcok) {
                            successBlcok(model);
                        }
                    }
                    else
                    {
                        if (failedBlcok) {
                            failedBlcok(error.localizedDescription);
                        }
                    }
                }](nil,responseObject,aClass);
                
            }
            else
            {
            
                if ([weakSelf connectedToNetwork]==NO) {
                    
                    failedBlcok(@"无法联系网络...");
                    return;
                }
                
                id newParam = [weakSelf onSetUpdateParam:param];
                
          
                
              NSURLSessionDataTask *dataTask = [weakSelf.netTool POST:url parameters:newParam progress:^(NSProgress * _Nonnull uploadProgress) {
                    
                    
                } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    
           if (![responseObject isKindOfClass:[NSDictionary class]]) {
                        responseObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                    }
                    
                    
                    [GBNetWorking checkHTTPStatusCodeWithModel:^(BOOL success, NSError *error, id model) {
                        if (success) {
                            if (successBlcok) {
                                successBlcok(model);
                            }
                        }
                        else
                        {
                            if (failedBlcok) {
                                failedBlcok(error.localizedDescription);
                            }
                        }
                         [weakSelf.requestDic removeObjectForKey:url];
                    }](task,responseObject,aClass);
                    
                    
                    if (cache) {
                        
                        [weakSelf storeObject:responseObject requestForKey:key];
                    }
                    
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    
                    
                    [GBNetWorking checkHTTPErrorStatusCode:^(NSError *error) {
                        NSString *str;
                        if ([error isKindOfClass:[NSDictionary class]]) {
                            NSDictionary *dic =error.userInfo;
                            str = dic[NSLocalizedDescriptionKey];
                        }else if ([error isKindOfClass:[NSError class]]){
                            str = error.localizedDescription;
                        }
                        if (errorBlcok) {
                            errorBlcok(str);
                        }
                         [weakSelf.requestDic removeObjectForKey:url];
                    }](task,error);
                    
                }];
                
                [weakSelf.requestDic removeObjectForKey:url];
                [weakSelf.requestDic setValue:dataTask forKey:url];
                
            }
            
        } cache:read];
 
    }
    else
    {
        if ([self connectedToNetwork]==NO) {
            
            failedBlcok(@"无法联系网络...");
            return;
        }
        
        WSELF(weakSelf);
        
//        id newParam = [self onSetUpdateParam:param];
        
//      [self.netTool.requestSerializer setValue:@"JSESSIONID=22EEFF18C21BF2033C75ED47C038B43F,AccessKey=JSESSIONID=22EEFF18C21BF2033C75ED47C038B43F" forHTTPHeaderField:@"Cookie"];
        
       NSURLSessionDataTask *dataTask = [weakSelf.netTool POST:url parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
            
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            if (![responseObject isKindOfClass:[NSDictionary class]]&&responseObject !=nil) {
                responseObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            }
            
            if (cache) {
                NSString * key = [weakSelf keyWithParameters:param];
                [weakSelf storeObject:responseObject requestForKey:key];
            }
            
            [GBNetWorking checkHTTPStatusCodeWithModel:^(BOOL success, NSError *error, id model) {
                if (success) {
                    if (successBlcok) {
                        successBlcok(model);
                    }
                }
                else
                {
                    if (failedBlcok) {
                        failedBlcok(error.localizedDescription);
                    }
                }
            [weakSelf.requestDic removeObjectForKey:url];
            }](task,responseObject,aClass);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            
            [GBNetWorking checkHTTPErrorStatusCode:^(NSError *error) {
                NSString *str;
                if ([error isKindOfClass:[NSDictionary class]]) {
                    NSDictionary *dic =error.userInfo;
                    str = dic[NSLocalizedDescriptionKey];
                }else if ([error isKindOfClass:[NSError class]]){
                    str = error.localizedDescription;
                }
                if (errorBlcok) {
                    errorBlcok(str);
                }
                [weakSelf.requestDic removeObjectForKey:url];
            }](task,error);
            
        }];
        
        [self.requestDic removeObjectForKey:url];
        [self.requestDic setValue:dataTask forKey:url];

    }
    

}

-(void)cancelRequest:(NSString *)key
{
    NSURLSessionDataTask *dataTask = [self.requestDic objectForKey:key];
    [dataTask cancel];
    [self.requestDic removeObjectForKey:key];
    
}

- (void)GET:(NSString *)url
      param:(id)param
 parseClass:(Class)aClass
successBlock:(void (^)(id data))successBlcok
 falieBlock:(void (^)(NSString *error))failedBlcok
 errorBlock:(void (^)(id error))errorBlcok
{
    if ([self connectedToNetwork]==NO) {
        
        failedBlcok(@"无法联系网络...");
        return;
    }
    
    WSELF(weakSelf);
    
    //        id newParam = [self onSetUpdateParam:param];
    
    NSURLSessionDataTask *dataTask = [weakSelf.netTool GET:url parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (![responseObject isKindOfClass:[NSDictionary class]]) {
            responseObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        }
        
//        if (cache) {
//            NSString * key = [weakSelf keyWithParameters:param];
//            [weakSelf storeObject:responseObject requestForKey:key];
//        }
        
        [GBNetWorking checkHTTPStatusCodeWithModel:^(BOOL success, NSError *error, id model) {
            if (success) {
                if (successBlcok) {
                    successBlcok(model);
                }
            }
            else
            {
                if (failedBlcok) {
                    failedBlcok(error.localizedDescription);
                }
            }
            [weakSelf.requestDic removeObjectForKey:url];
        }](task,responseObject,aClass);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
        [GBNetWorking checkHTTPErrorStatusCode:^(NSError *error) {
            NSString *str;
            if ([error isKindOfClass:[NSDictionary class]]) {
                NSDictionary *dic =error.userInfo;
                str = dic[NSLocalizedDescriptionKey];
            }else if ([error isKindOfClass:[NSError class]]){
                str = error.localizedDescription;
            }
            if (errorBlcok) {
                errorBlcok(str);
            }
            [weakSelf.requestDic removeObjectForKey:url];
        }](task,error);
        
    }];
    
    [self.requestDic removeObjectForKey:url];
    [self.requestDic setValue:dataTask forKey:url];

}

- (void)Download:(NSString *)url1
param:(NSDictionary *)param
    successBlock:(void (^)(id data))successBlcok
      falieBlock:(void (^)(NSString *error))failedBlcok
{
    
    
    url1 = [[NSString stringWithFormat:@"%@%@",host,url1]  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//
    
    
    /* 创建网络下载对象 */
//    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    
//    /* 下载地址 */
//    NSURL *url = [NSURL URLWithString:url1];
//    NSURLRequest *request = [NSURLRequest requestWithURL:url];
//    AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
//    NSMutableURLRequest *request =[[manager requestSerializer]requestWithMethod:@"POST" URLString:url1 parameters:param error:nil];

    
    /* 下载路径 */
//    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
//    NSString *filePath = [path stringByAppendingPathComponent:url.lastPathComponent];
//
    /* 开始请求下载 */
   WSELF(weakSelf);
//    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
//        NSLog(@"下载进度：%.0f％", downloadProgress.fractionCompleted * 100);
//    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
//
//        if(![weakSelf isFileExist:[response suggestedFilename]]) {
//            NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
//            //        [response suggestedFilename]为文件名
//            NSURL *url = [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
//            return url;
//        }else
//        {
//            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//            NSString *path = [paths objectAtIndex:0];
//            NSString *filePath = [path stringByAppendingPathComponent:[response suggestedFilename]];
//            return [NSURL fileURLWithPath:filePath];
//        }
//
//
//    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
//        NSLog(@"下载完成");
//
//    }];
//    [downloadTask resume];
    
//    WSELF(weakSelf);
//    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
//
//        NSLog(@"下载进度：%.0f％", downloadProgress.fractionCompleted * 100);
//
//    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
//
//        NSLog(@"%@---%@----%@",targetPath,response,[response suggestedFilename]);
//
//        if(![weakSelf isFileExist:[response suggestedFilename]]) {
//            NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
//            //        [response suggestedFilename]为文件名
//            NSURL *url = [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
//            return url;
//        }else
//        {
//            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//            NSString *path = [paths objectAtIndex:0];
//            NSString *filePath = [path stringByAppendingPathComponent:[response suggestedFilename]];
//            return [NSURL fileURLWithPath:filePath];
//        }
//
//
//    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
//
//        NSLog(@"下载完成");
//
//    }];
//    [downloadTask resume];
    
//    NSURL *URL = [NSURL URLWithString:url];
//    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
//    NSString * json =  AFQueryStringFromParameters(param);
//    NSData *data = [json dataUsingEncoding:NSUTF8StringEncoding];
//    request.HTTPBody = data;
//
    
    
    //沙盒路径    //NSString *savedPath = [NSHomeDirectory() stringByAppendingString:@"/Documents/xxx.zip"];
    AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
    NSMutableURLRequest *request =[serializer requestWithMethod:@"POST" URLString:url1 parameters:param error:nil];

    NSURLSessionDownloadTask *downloadTask = [self.netTool downloadTaskWithRequest:request progress:^(NSProgress *downloadProgress){
        NSLog(@"%f",(CGFloat)downloadProgress.completedUnitCount/(CGFloat)downloadProgress.totalUnitCount);
    } destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {

        NSLog(@"%@---%@----%@",targetPath,response,[response suggestedFilename]);

        if(![weakSelf isFileExist:[response suggestedFilename]]) {
            NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
            //        [response suggestedFilename]为文件名
            NSURL *url = [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
            return url;
        }else
        {
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *path = [paths objectAtIndex:0];
            NSString *filePath = [path stringByAppendingPathComponent:[response suggestedFilename]];
            return [NSURL fileURLWithPath:filePath];
        }

    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        if (error) {
            if (failedBlcok) {
                failedBlcok(error.localizedDescription);
            }
        }else
        {
            if (successBlcok) {
                successBlcok(filePath);
            }
        }
    }];
    [downloadTask resume];

    
    //以下是手动创建request方法 AFQueryStringFromParametersWithEncoding有时候会保存
//        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestURL]];
//       NSMutableURLRequest *request =[[[AFHTTPRequestOperationManager manager]requestSerializer]requestWithMethod:@"POST" URLString:requestURL parameters:paramaterDic error:nil];
    //
    //    NSString *charset = (__bridge NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    //
    //    [request setValue:[NSString stringWithFormat:@"application/x-www-form-urlencoded; charset=%@", charset] forHTTPHeaderField:@"Content-Type"];
    //    [request setHTTPMethod:@"POST"];
    //
    //    [request setHTTPBody:[AFQueryStringFromParametersWithEncoding(paramaterDic, NSASCIIStringEncoding) dataUsingEncoding:NSUTF8StringEncoding]];
    
//    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
//    [operation setOutputStream:[NSOutputStream outputStreamToFileAtPath:savedPath append:NO]];
//    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
//        float p = (float)totalBytesRead / totalBytesExpectedToRead;
//
//        NSLog(@"download：%f", (float)totalBytesRead / totalBytesExpectedToRead);
//
//    }];
//
//    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//
//        NSLog(@"下载成功");
//
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//
//        NSLog(@"下载失败");
//
//    }];
//
//    [operation start];

    /* 下载地址 */


//    manager.requestSerializer= [AFHTTPRequestSerializer
//                                serializer];
//    manager.responseSerializer= [AFHTTPResponseSerializer serializer];
//
//
//    NSURLSessionDownloadTask*download =   [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
//
//    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
//
//
//        NSError*error = nil;
//        NSURL*URL = [[NSFileManager defaultManager]URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:&error];
//
//        //告诉服务器文件保存在哪
//        return[URL URLByAppendingPathComponent:[response suggestedFilename]isDirectory:NO];
//
//    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
//         NSLog(@"response:%@,filePath:%@,error%@",response,filePath,error.localizedDescription);
//    }];
//
//    [download resume];
    
}
//判断文件是否已经在沙盒中存在
-(BOOL) isFileExist:(NSString *)fileName
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSString *filePath = [path stringByAppendingPathComponent:fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL result = [fileManager fileExistsAtPath:filePath];
    NSLog(@"这个文件已经存在：%@",result?@"是的":@"不存在");
    return result;
}


@end
